﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace Lincolnwood.Foundation.Common.Data.NHibernate
{

    public class NHibernateHelper
    {
        private Configuration _configuration;
        private ISessionFactory _sessionFactory;

        public Configuration Configuration
        {
            get
            {
                if (_configuration == null)
                {
                    _configuration = new Configuration();
                    _configuration.Configure();
                }
                return _configuration;
            }
        }

        public Configuration ConfigureWith(System.Reflection.Assembly hbmAssembly)
        {            
            Configuration.AddAssembly(hbmAssembly);
            return _configuration;
        }

        public ISession OpenSession()
        {
            if (_sessionFactory == null)
            {
                _sessionFactory = Configuration.BuildSessionFactory();
            }
            return _sessionFactory.OpenSession();
        }

        public ISession OpenSession(Configuration config)
        {
            ISessionFactory factory = config.BuildSessionFactory();
            return factory.OpenSession();
        }

        public void GenerateSchema()
        {
            new SchemaExport(Configuration).Execute(true, true, false);
        }
    }
}
